package com.baichuan.zntx.handler;

import com.baichuan.zntx.domain.DataMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author mazhanliang
 */
public class MessageDecodeHandler extends ByteToMessageDecoder {
    //$data,1,74,1,2,3,1.00000,1.00000,0,1,1,0,27,0,end
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // 获取客户端的远程地址
        InetSocketAddress remoteAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
        // 获取IP地址
        String clientIP = remoteAddress.getAddress().getHostAddress();
        ByteBuf frame = byteBuf.retainedDuplicate();
        //客户端获取IP地址
        String content = frame.toString(CharsetUtil.UTF_8);
        //删除开始字符
        if(content.startsWith("$")){
            content = content.replace("$","");
        }
        DataMessage message = new DataMessage(clientIP, content);
        list.add(message);
        byteBuf.skipBytes(byteBuf.readableBytes());
    }
}
